import { useInternalModuleTagsViewStore } from '@/stores/internalModuleTagsView'
import { useSystemStore } from '@/stores/system'
import { useToggle } from '@vueuse/core'
import { nextTick, unref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

export const useRouteQuery = async (callback, opts = {}) => {
    const { clearQuery = true } = opts
    const route = useRoute()
    const router = useRouter()
    const query = route.query
    await callback({ route, router, query })
    clearQuery && router.replace({ query: {}})
}

const [isReloadLayoutPage, toggleReloadLayoutPage] = useToggle(false)

export const useReloadLayoutPage = () => {
    const router = useRouter()

    const reloadPage = async () => {
        toggleReloadLayoutPage(true)
        await nextTick()
        toggleReloadLayoutPage(false)
    }

    return {
        isReloadPage: isReloadLayoutPage,
        toggleReloadPage: toggleReloadLayoutPage,
        reloadPage
    }
}

const [isReloadInternalModulePage, toggleReloadInternalModulePage] = useToggle(false)

export const useReloadInternalModulePage = () => {
    const router = useRouter()
    const internalModuleTagsViewStore = useInternalModuleTagsViewStore()

    const reloadPage = async () => {
        const _route = Object.assign({}, unref(router.currentRoute))
        const { _componentName } = _route.meta
        internalModuleTagsViewStore.addExclude(_componentName)
        toggleReloadInternalModulePage(true)
        await nextTick()
        toggleReloadInternalModulePage(false)
        internalModuleTagsViewStore.deleteExclude(_componentName)
    }

    const reloadTo = (moduleComponentName, /** @type {import('vue-router').RouteLocationRaw} */ to) => {
        const menuItem = findMenuItemByModuleComponentName(moduleComponentName)
        if (!menuItem) return

        const internalModuleTagsViewStore = useInternalModuleTagsViewStore()
        internalModuleTagsViewStore.addExclude(menuItem._componentName)

        return router.push({
            ...to,
            path: menuItem._path
        }).then(() => {
            internalModuleTagsViewStore.deleteExclude(menuItem._componentName)
        })
    }

    return {
        isReloadPage: isReloadInternalModulePage,
        toggleReloadPage: toggleReloadInternalModulePage,
        reloadPage,
        reloadTo
    }
}

export const findMenuItemByModuleComponentName = (moduleComponentName = '') => {
    const systemStore = useSystemStore()
    for (let i = 0; i < systemStore.navList.length; i++) {
        const navItem = systemStore.navList[i]
        if (navItem.subSystemType !== 0) continue
        const { _menuList = [] } = navItem
        const menuItem = _menuList.find(it => it._moduleComponentName === moduleComponentName)
        if (menuItem) return menuItem
        else continue
    }
}